package com.by.service.impl;

import com.by.bean.CustomerInquiry;
import com.by.common.utils.Assert;
import com.by.common.utils.DateUtils;
import com.by.mapper.CustomerInquiryDetailMapper;
import com.by.mapper.CustomerInquiryMapper;
import com.by.service.CustomerInquiryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerInquiryServiceImpl implements CustomerInquiryService {
    @Autowired
    CustomerInquiryMapper customerInquiryMapper;
    @Autowired
    CustomerInquiryDetailMapper customerInquiryDetailMapper;
    //设置最大编码
    String maxCode;
    @Override
    public int save(CustomerInquiry entity) {
        //生成询价编码
        entity.setCode(generateNewCode());
        int res = customerInquiryMapper.save(entity);
        Assert.isZero(res,"保存客户询价单失败");
        if(null!=entity.getCustomerInquiryDetailLists()&&entity.getCustomerInquiryDetailLists().size()>0){
            res=customerInquiryDetailMapper.batchSave(entity.getId(),entity.getCustomerInquiryDetailLists());
            Assert.isZero(res,"保存客户询价明细失败");
        }
        return 1;
    }
    String generateNewCode(){
        String ym= DateUtils.getSystemTimeYM();
        //判断最大编码是否存在
        if(null==maxCode){
            //如果不存在查询数据库
            maxCode= customerInquiryMapper.queryMaxCode();
            if(null==maxCode){
                maxCode="KHXJ"+ym+"0001";
                return maxCode;
            }
        }
        //执行到这里  获取最大编码 KHXJ25030001  计算新的编码
        //提取编码中的日期  2503
        String tepYm= maxCode.substring(4,8);
        if(!ym.equals(tepYm)){
            //说明当前最大编码不是当月的编码
            maxCode = "KHXJ" + ym + "0001";
            return maxCode;
        }
        //如果到这里 是当月的最大编码  序号累加 KHXJ25030001
        String prefix = maxCode.substring(0, 8);
        String seq = maxCode.substring(8);
        int num = Integer.parseInt(seq);
        num++;
        maxCode = prefix + String.format("%04d", num);
        return maxCode;
    }
}
